<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>修改头像</span>
      </div>
      <div>
        <el-upload
          action="http://localhost:3000/api/upload/avatarupload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
          :on-progress="handleProgress"
          :before-upload="beforeAvatarUpload"
          :limit="1"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt />
        </el-dialog>
        <el-button class="resetAvatar" type="primary" @click="submitForm()">立即创建</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { delUploadImg, resetAvatar } from "@/api/user";
export default {
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      filename: "",
      avatarUrl: ""
    };
  },
  methods: {
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isLt2M;
    },
    // 删除图片
    async handleRemove(file, fileList) {
      // 如果filename不为空，就说明上传成功了
      if (this.filename !== "") {
        // 上传成功然后需要删除执行下面代码
        const data = { filename: this.filename };
        await delUploadImg(data)
          .then(res => {
            console.log(res);
          })
          .catch(err => {
            console.log(err);
          });
      }
    },
    // 图片放大
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 图片上传成功
    handleSuccess(response, file, fileList) {
      if (response.code == 200) {
        this.filename = response.filename;
        this.avatarUrl = response.fileUrl;
        this.$message.success("上传成功");
      } else {
        this.$message.error("上传失败");
      }
    },
    // 图片上传过程
    handleProgress(event, file, fileList) {},
    // 提交修改头像申请
    async submitForm() {
      this.$confirm("是否要修改头像", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const userInfo = JSON.parse(localStorage.getItem("userInfo"));
          const data = { id: userInfo.id, avatarUrl: this.avatarUrl };
          await resetAvatar(data)
            .then(res => {
              if (res.data.code == 200) {
                // 修改成功后改变本地存储的信息
                userInfo.profile = this.avatarUrl;
                localStorage.setItem("userInfo", JSON.stringify(userInfo));
                location.reload()
              }
            })
            .catch(err => {});
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    }
  }
};
</script>

<style scoped lang="less">
.head-border {
  width: 180px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.head-border:hover {
  border: 1px dashed #409eff;
}
.avatar {
  width: 180px;
  height: 180px;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.resetAvatar {
  margin-top: 20px;
  width: 148px;
}
</style>

